package br.com.twit4bus.conf;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.http.AccessToken;
import twitter4j.http.RequestToken;

import java.io.*;
import java.util.Properties;

public class GetAcessToken {
    /**
     * Usage: java  twit4bus.examples.oauth.GetAccessToken [consumer key] [consumer secret]
     * @param args message
     */

	public static void main (String args[]) {
		AtualizaTokens("FnmOy32pnGp761JrJk47Q","80nRiKsrsqUF2QueAvorTHRQgYocUh54R1e8x2Amd4");
	}

    public static void AtualizaTokens ( String consumerKey , String consumerSecret ) {
        
    	File file = new File("twit4bus.properties");
        Properties prop = new Properties();
        InputStream is = null;
        OutputStream os = null;

        try{
            if (file.exists()) {
                is = new FileInputStream(file);
                prop.load(is);
            }
            if(consumerKey.isEmpty() || consumerSecret.isEmpty()) {
                if (null == prop.getProperty("oauth.consumerKey")
                        && null == prop.getProperty("oauth.consumerSecret")) {
                    // consumer key/secret are not set in twit4bus.properties
                    System.out.println(
                            "Usage: java twit4bus.examples.oauth.GetAccessToken [consumer key] [consumer secret]");
                    System.exit(-1);
                }
            }else{
                prop.setProperty("oauth.consumerKey", consumerKey );
                prop.setProperty("oauth.consumerSecret", consumerSecret );
                os = new FileOutputStream("twit4bus.properties");
                prop.store(os, "twit4bus.properties");
            }
        }catch(IOException ioe){
            ioe.printStackTrace();
            System.exit(-1);
        }finally{
            if(null != is){
                try {
                    is.close();
                } catch (IOException ignore) {
                }
            }
            if(null != os){
                try {
                    os.close();
                } catch (IOException ignore) {
                }
            }
        }

        try {
            Twitter twitter = new TwitterFactory().getInstance();
            twitter.setOAuthConsumer(consumerKey, consumerSecret);
            RequestToken requestToken = twitter.getOAuthRequestToken();
            System.out.println("Got request token.");
            System.out.println("Request token: "+ requestToken.getToken());
            System.out.println("Request token secret: "+ requestToken.getTokenSecret());
            AccessToken accessToken = null;

            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            while (null == accessToken) {
                System.out.println("Open the following URL and grant access to your account:");
                System.out.println(requestToken.getAuthorizationURL());
                System.out.print("Enter the PIN(if available) and hit enter after you granted access.[PIN]:");
                String pin = br.readLine();
                try{
                    if(pin.length() > 0){
                        accessToken = twitter.getOAuthAccessToken(requestToken, pin);
                    }else{
                        accessToken = twitter.getOAuthAccessToken(requestToken);
                    }
                } catch (TwitterException te) {
                    if(401 == te.getStatusCode()){
                        System.out.println("Unable to get the access token.");
                    }else{
                        te.printStackTrace();
                    }
                }
            }

            System.out.println("Got access token.");
            System.out.println("Access token: " + accessToken.getToken());
            System.out.println("Access token secret: " + accessToken.getTokenSecret());

            try {
                prop.setProperty("oauth.accessToken", accessToken.getToken());
                prop.setProperty("oauth.accessTokenSecret", accessToken.getTokenSecret());
                os = new FileOutputStream(file);
                prop.store(os, "twit4bus.properties");
                os.close();
            } catch (IOException ioe) {
                ioe.printStackTrace();
                System.exit(-1);
            } finally {
                if (null != os) {
                    try {
                        os.close();
                    } catch (IOException ignore) {
                    }
                }
            }
            System.out.println("Successfully stored access token to " + file.getAbsolutePath()+ ".");
            System.exit(0);
        } catch (TwitterException te) {
            te.printStackTrace();
            System.out.println("Failed to get accessToken: " + te.getMessage());
            System.exit( -1);
        } catch (IOException ioe) {
            ioe.printStackTrace();
            System.out.println("Failed to read the system input.");
            System.exit( -1);
        }
    }
}